package com.mac.hosp_pre.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mac.hosp_pre.admin.mapper.DictMapper;
import com.mac.hosp_pre.admin.entity.Dict;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.admin.listener.DictExcelListener;
import com.mac.hosp_pre.admin.model.resp.DictExcelDto;
import com.mac.hosp_pre.admin.model.resp.DictRespDto;
import com.mac.hosp_pre.admin.model.resp.ExcErrorInfoDto;
import com.mac.hosp_pre.admin.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict#240",keyGenerator = "keyGenerator")
    public List<DictRespDto> findChlidData(Long id) {
        List<Dict> dictList = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        if (CollectionUtil.isNotEmpty(dictList)){
            return dictList.stream().map(item -> {
                DictRespDto respDto = new DictRespDto();
                BeanUtils.copyProperties(item, respDto);
                boolean isChild = this.isChildren(item.getId());
                respDto.setHasChildren(isChild);
                return respDto;
            }).collect(Collectors.toList());
        }
        return null;
    }

    //导出数据字典接口
    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //Dict -- DictEeVo
        List<DictExcelDto> dictVoList = new ArrayList<>();
        for(Dict dict : dictList) {
            DictExcelDto dictEeVo = new DictExcelDto();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);
        }
        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictExcelDto.class).sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {
           log.error("导出数据字典失败:{}",e);
        }
    }

    //导入数据字典
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public List<ExcErrorInfoDto> importDictData(MultipartFile file) {
        List<ExcErrorInfoDto> errorInfoDtos = new ArrayList<>();
        try {
            EasyExcel.read(file.getInputStream(),DictExcelDto.class,new DictExcelListener(1000,this,errorInfoDtos))
                    .sheet().doRead();
            return errorInfoDtos;
        } catch (IOException e) {
            throw new ServiceException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    //根据dictcode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if(!StringUtils.hasText(dictCode)) {
            //直接根据value查询
            Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getVal,value));
            if (dict == null) {
                return null;
            }
            return dict.getName();
        } else {//如果dictCode不为空，根据dictCode和value查询
            //根据dictcode查询dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            if (codeDict == null) {
                return null;
            }
            //根据parent_id和value进行查询
            Dict finalDict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getVal,value)
                    .eq(Dict::getParentId,codeDict.getId()));
            if (finalDict == null) {
                return null;
            }
            return finalDict.getName();
        }
    }

    //根据dictCode获取下级节点
    @Override
    public List<DictRespDto> findByDictCode(String dictCode) {
        //根据dictcode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        if (dict == null) {
            return null;
        }
        //根据id获取子节点
        return this.findChlidData(dict.getId());
    }

    private Dict getDictByDictCode(String dictCode) {
        Dict codeDict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
        return codeDict;
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        Long count = this.count(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        return count > 0;
    }
}
